import User.User;
import User.Duser;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(name = "uploadImg")
@MultipartConfig(location = "E:\\local-maven\\实验4\\src\\main\\webapp\\userimags")
public class uploadImg extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Part part = request.getPart("img");
        String fileName = part.getSubmittedFileName();
        part.write(fileName);
        String str="userimags/"+fileName;
        User user = (User) request.getSession().getAttribute("SELF");

        if(user != null) {
            if (str != null) user.setImg(str);
            request.getSession().setAttribute("SELF", user);
            if (Treatment.uploadimg(user)) {
                System.out.println("更改头像成功！");
            }
            else {
                System.out.println("更换头像失败！");
                response.sendRedirect("/error.jsp");
            }
            if(user.getDgutid() != null)
            {
                EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyDSTest");
                EntityManager entityManager = entityManagerFactory.createEntityManager();
                Duser duser = entityManager.find(Duser.class, user.getDgutid());
                duser.setImg(str);
                request.getSession().setAttribute("DGUT", duser);
                if(Treatment.uploadimg2(duser))
                {
                    System.out.println("更改头像成功！");
                }
                else
                {
                    System.out.println("更换头像失败！");
                    response.sendRedirect("/error.jsp");
                }
            }
            response.sendRedirect("/user.jsp");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
